package org.bookie.init.tasks;

import java.util.Properties;

import org.apache.hivemind.Registry;
import org.bookie.init.InitTask;
import org.bookie.model.Role;
import org.bookie.model.User;
import org.bookie.model.services.UserDAO;

public class UserLoad implements InitTask {
	private static final String DOMAIN = "freebookie.org";
	public static final String HOMER_EMAIL = "homer@"+DOMAIN;
	public static final String SIMPSON = "Simpson";
	public static final String BOUVIER = "Bouvier";
	public static final String FLANDERS = "Flanders";
	
	User homer = new User("Homer Simpson", "test", HOMER_EMAIL);
	
	private User[] users = new User[]{
			homer,
			new User("Marge "+SIMPSON, "test", "marge@"+DOMAIN),
			new User("Bart "+SIMPSON, "test", "bart@"+DOMAIN),
			new User("Lisa "+SIMPSON, "test", "lias@"+DOMAIN),
			new User("Abraham "+SIMPSON, "test", "abraham@"+DOMAIN),
			new User("Mona J. "+SIMPSON, "test", "mona@"+DOMAIN),
			new User("Jacqueline "+BOUVIER, "test", "jacqueline@"+DOMAIN),
			new User("Selma "+BOUVIER, "test", "selma@"+DOMAIN),
			new User("Ned "+FLANDERS, "test", "ned@"+DOMAIN),
			new User("Maude "+FLANDERS, "test", "maude@"+DOMAIN),
			new User("Charles Montgomery Burns", "test", "charles@"+DOMAIN),
			new User("Carl Carlson", "test", "carl@"+DOMAIN),
			new User("Herschel Krustofsky", "test", "herschel@"+DOMAIN),
			new User("Apu Nahasapeemapetilon", "test", "apu@"+DOMAIN),
			new User("Sanjay Nahasapeemapetilon", "test", "sanjay@"+DOMAIN)};
	
	

	
	public UserLoad() {
		for(User user:users){
			user.setRole(Role.USER);
		}
		homer.setRole(Role.ADMIN);
	}
	
	public Properties check(Registry reg) throws Exception {
		Properties result = new Properties();
		UserDAO dao = (UserDAO) reg.getService(UserDAO.class);
		for(User user:users){
			checkUser(result, dao, user);
		}
		return result;
	}

	private void checkUser(Properties result, UserDAO dao, User user) {
		boolean foundUser = dao.findByEmail(user.getEmail()) != null;
		result.put("User '"+user.getEmail()+"' is found", String.valueOf(foundUser));
	}

	public Properties execute(Registry reg) throws Exception {
		Properties result = new Properties();
		UserDAO dao = (UserDAO) reg.getService(UserDAO.class);
		for(User user:users){
			executeUser(result, dao, user);
		}
		return result;
	}

	private void executeUser(Properties result, UserDAO dao, User user) {
		if (dao.findByEmail(user.getEmail()) == null) {
			dao.makePersistent(user);
			result.put("New User " + user.getEmail() + " created", "OK");
		} else {
			result.put("User " + user.getEmail() + " creation", "Skipped");
		}
	}

	public String getTitle() {
		return "User data load";
	}

}
